﻿Imports System.Data.OleDb

' Nicht MultiThreadingfähig !!!
Public Class Connection

    Protected Shared con As New OleDbConnection
    Protected Shared cmd As New OleDbCommand
    Protected Shared reader As OleDbDataReader

    Private Shared connectionsCounter As Integer = 0

    Public Shared Sub open()
        If connectionsCounter = 0 Then
            con.ConnectionString = PropertiesHandler.getValue("db.connectionstring")
            cmd.Connection = con
            con.Open()
        End If
        connectionsCounter = connectionsCounter + 1
    End Sub

    Public Shared Sub beginTransaction()
        cmd.Transaction = con.BeginTransaction
    End Sub

    Public Shared Sub commitTransatcion()
        cmd.Transaction.Commit()
    End Sub

    Public Shared Sub rollbackTransaction()
        cmd.Transaction.Rollback()
    End Sub

    Public Shared Sub close()
        If connectionsCounter = 1 Then
            con.Close()
        End If
        connectionsCounter = connectionsCounter - 1
    End Sub

    Public Shared Function executeReader(ByRef query As Query) As OleDbDataReader
        closeReader()
        cmd.CommandText = query.sql
        Try
            reader = cmd.ExecuteReader
        Catch ex As OleDb.OleDbException
            MsgBox(ex.Message & ": " & query.sql)
        End Try
        Return reader
    End Function

    Public Shared Sub executeNonQuery(ByRef query As Query)
        closeReader()
        cmd.CommandText = query.sql
        Try
            cmd.ExecuteNonQuery()
        Catch ex As OleDb.OleDbException
            MsgBox(ex.Message & ": " & query.sql)
        End Try
    End Sub

    Private Shared Sub closeReader()
        If Not reader Is Nothing Then
            If Not reader.IsClosed Then
                reader.Close()
            End If
        End If
    End Sub
End Class
